
#include "thread.h"
#include "ipc.h"

#include "gpio.h"

#define KEY1 GET_PIN_NBR(GPIOA, 0)
#define KEY2 GET_PIN_NBR(GPIOC, 13)

#define LED1 GET_PIN_NBR(GPIOB, 0)
#define LED2 GET_PIN_NBR(GPIOB, 1)

static mt_sem_t *key1, *key2;

static void pin_callbk(void *arg)
{
    uint32_t data = (uint32_t)arg;
    
    if(KEY1 == data)
        mt_sem_release(key1);
    if(KEY2 == data)
        mt_sem_release(key2);
}

static void *led1_func(void *arg)
{
    int32_t led_state = PIN_LOW;
    
    mt_pin_write(LED1, led_state);
    mt_pin_config(LED1, PIN_MODE_OUTPUT_PP, PIN_NOPULL);
    mt_pin_config(KEY1, PIN_MODE_IRQ_RISING, PIN_NOPULL);
    mt_pin_attach_irq(KEY1, pin_callbk, (void *)KEY1);
    mt_pin_enable_irq(KEY1, 1);
    
    while(1)
    {
        if(mt_sem_take(key1, MT_WAITING_FOREVER) == MT_EOK)
        {
            if(led_state == PIN_HIGH)
                led_state = PIN_LOW;
            else
                led_state = PIN_HIGH;
            mt_pin_write(LED1, led_state);
            mt_delay(20);
        }
        else
            printf("key1 take failed\r\n");
    }
}

static void *led2_func(void *arg)
{
    int32_t led_state = PIN_LOW;
    
    mt_pin_write(LED1, led_state);
    mt_pin_config(LED2, PIN_MODE_OUTPUT_PP, PIN_NOPULL);
    mt_pin_config(KEY2, PIN_MODE_IRQ_RISING, PIN_NOPULL);
    mt_pin_attach_irq(KEY2, pin_callbk, (void *)KEY2);
    mt_pin_enable_irq(KEY2, 1);
    
    while(1)
    {
        if(mt_sem_take(key2, MT_WAITING_FOREVER) == MT_EOK)
        {
            if(led_state == PIN_HIGH)
                led_state = PIN_LOW;
            else
                led_state = PIN_HIGH;
            mt_pin_write(LED2, led_state);
            mt_delay(20);
        }
        else
            printf("key2 take failed\r\n");
    }
}

int gpio_test(void)
{
    mt_thread_t *led1_handle, *led2_handle;
    
    key1 = mt_sem_create("key1", 
                         0, 
                         0, 
                         MT_IPC_FLAG_FIFO);
    key2 = mt_sem_create("key2", 
                         0, 
                         0, 
                         MT_IPC_FLAG_FIFO);
    if((key1 == MT_NULL) || (key2 == MT_NULL))
    {
        printf("create sem faied\r\n");
        return -1;
    }
    
    led1_handle = mt_thread_create("led1_func", 
                                   led1_func, 
                                   MT_NULL, 
                                   1024, 
                                   1, 
                                   5);
    led2_handle = mt_thread_create("led2_func", 
                                   led2_func, 
                                   MT_NULL, 
                                   1024, 
                                   1, 
                                   5);
    if((led1_handle == MT_NULL) || (led2_handle == MT_NULL))
    {
        printf("create thrtead faied\r\n");
        return -1;
    }
    mt_thread_start(led1_handle);
    mt_thread_start(led2_handle);
    
    return 0;
}
